<?php

class Megadrupal_Slider_Adminhtml_SliderController extends Mage_Adminhtml_Controller_Action {

    protected function _initAction() {
        $this->loadLayout()->_setActiveMenu("slider/slider")->_addBreadcrumb(Mage::helper("adminhtml")->__("Slider  Manager"), Mage::helper("adminhtml")->__("Slider Manager"));
        return $this;
    }

    public function indexAction() {
        $this->_title($this->__("Slider"));
        $this->_title($this->__("Manager Slider"));

        $this->_initAction();
        $this->renderLayout();
    }

    public function editAction() {       
        $this->_title($this->__("Slider"));
        $this->_title($this->__("Slider"));
        $this->_title($this->__("Edit Item"));

        $id = $this->getRequest()->getParam("id");
        $model = Mage::getModel("slider/slider")->load($id);
        if ($model->getId()) {
            Mage::register("slider_data", $model);
            $this->loadLayout();
            $this->_setActiveMenu("slider/slider");
            $this->_addBreadcrumb(Mage::helper("adminhtml")->__("Slider Manager"), Mage::helper("adminhtml")->__("Slider Manager"));
            $this->_addBreadcrumb(Mage::helper("adminhtml")->__("Slider Description"), Mage::helper("adminhtml")->__("Slider Description"));
            $this->getLayout()->getBlock("head")->setCanLoadExtJs(true);
            $this->_addContent($this->getLayout()->createBlock("slider/adminhtml_slider_edit"))->_addLeft($this->getLayout()->createBlock("slider/adminhtml_slider_edit_tabs"));
            $this->renderLayout();
        } else {
            Mage::getSingleton("adminhtml/session")->addError(Mage::helper("slider")->__("Item does not exist."));
            $this->_redirect("*/*/");
        }
    }

    public function newAction() {
     
        $this->_title($this->__("Slider"));
        $this->_title($this->__("Slider"));
        $this->_title($this->__("New Item"));

        $id = $this->getRequest()->getParam("id");
        $model = Mage::getModel("slider/slider")->load($id);

        $data = Mage::getSingleton("adminhtml/session")->getFormData(true);
        if (!empty($data)) {
            $model->setData($data);
        }

        Mage::register("slider_data", $model);

        $this->loadLayout();
        $this->_setActiveMenu("slider/slider");

        $this->getLayout()->getBlock("head")->setCanLoadExtJs(true);

        $this->_addBreadcrumb(Mage::helper("adminhtml")->__("Slider Manager"), Mage::helper("adminhtml")->__("Slider Manager"));
        $this->_addBreadcrumb(Mage::helper("adminhtml")->__("Slider Description"), Mage::helper("adminhtml")->__("Slider Description"));


        $this->_addContent($this->getLayout()->createBlock("slider/adminhtml_slider_edit"))->_addLeft($this->getLayout()->createBlock("slider/adminhtml_slider_edit_tabs"));

        $this->renderLayout();
    }

    public function saveAction() {
        $post_data = $this->getRequest()->getPost();
        if ($post_data) {
            try {
                // Get and set data for Slider
                $sliderId = $this->getRequest()->getParam("id");
                $_sliderData['title'] = $post_data['title'];
                $_sliderData['description'] = $post_data['description'];
                $_sliderData['machine_name'] = $post_data['machine_name'];                
                $_sliderData['settings'] = serialize($post_data['setting']); 
                if($sliderId <= 0 && $_sliderData['machine_name'] == '') {
                    $_sliderData['machine_name'] = 'md_slider_'.time();
                }

                // Save Slider
                $model = Mage::getModel("slider/slider")
                        ->addData($_sliderData)
                        ->setId($sliderId)
                        ->save();
                                
                // Save Slide for this slider
                $_slides = json_decode($post_data['slides'], TRUE);
                if (count($_slides) > 0) {
                    foreach ($_slides as $skey => $_slide) {
                        $sid = $_slide['itemsetting']['slide_id'];
                        $_slideData['slid'] = $model->getSlid();                        
                        $_slideData['position'] = $skey;    
                        
                        // settings of slide
                        $_slideSettings['background_image'] = ($_slide['itemsetting']['fid'] != -1) ? $_slide['itemsetting']['fid']: 'images/default_bg.jpg';
                        $_slideSettings['timelinewidth'] = $_slide['itemsetting']['timelinewidth'];                                           
                        $_slideSettings['custom_thumbnail'] = $_slide['itemsetting']['thumb_fid'];
                        $_slideData['settings'] = serialize($_slideSettings);
                                           
                        // layers of slide
                        $_slideData['layers'] = serialize($_slide['boxitems']);
                        
                        $modelSlide = Mage::getModel("slider/slide");
                        if($sid > 0) {
                            // Save Slide
                            $modelSlide->addData($_slideData)->setId($sid)->save();
                        }else {                            
                            // Create Slide
                            $modelSlide->addData($_slideData)->save();
                        }
                    }
                }

                Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("Slider was successfully saved"));
                Mage::getSingleton("adminhtml/session")->setSliderData(false);

                if ($this->getRequest()->getParam("back")) {
                    $this->_redirect("*/*/edit", array("id" => $model->getSlid()));
                    return;
                }
                $this->_redirect("*/*/");
                return;
            } catch (Exception $e) {
                Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
                Mage::getSingleton("adminhtml/session")->setSliderData($this->getRequest()->getPost());
                $this->_redirect("*/*/edit", array("id" => $model->getSlid()));
                return;
            }
        }
        $this->_redirect("*/*/");
    }

    public function deleteAction() {
        if ($this->getRequest()->getParam("id") > 0) {
            try {
                $model = Mage::getModel("slider/slider");
                $model->setId($this->getRequest()->getParam("id"))->delete();
                
                // Delete Slide of this Slider
                $_resource = Mage::getSingleton('core/resource')->getConnection('core_write');
                $sql = "DELETE FROM md_slides WHERE slid=".$this->getRequest()->getParam("id");                     
                $_resource->query($sql);
                
                Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("Item was successfully deleted"));
                $this->_redirect("*/*/");
            } catch (Exception $e) {
                Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
                $this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
            }
        }
        $this->_redirect("*/*/");
    }
    public function deleteSlideAction() {
        $sid = $_REQUEST['sid'];
        
        if (Mage::getModel("slider/slide")->setId($sid)->delete()) {
          echo "OK";
        }else {
          echo "Can not delete slide: {$sid}";
        }      
        exit;
    }

    public function massRemoveAction() {
        try {
            $ids = $this->getRequest()->getPost('slids', array());
            foreach ($ids as $id) {
                $model = Mage::getModel("slider/slider");
                $model->setId($id)->delete();
            }
            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("Item(s) was successfully removed"));
        } catch (Exception $e) {
            Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
        }
        $this->_redirect('*/*/');
    }

    /**
     * Export order grid to CSV format
     */
    public function exportCsvAction() {
        $fileName = 'slider.csv';
        $grid = $this->getLayout()->createBlock('slider/adminhtml_slider_grid');
        $this->_prepareDownloadResponse($fileName, $grid->getCsvFile());
    }

    /**
     *  Export order grid to Excel XML format
     */
    public function exportExcelAction() {
        $fileName = 'slider.xml';
        $grid = $this->getLayout()->createBlock('slider/adminhtml_slider_grid');
        $this->_prepareDownloadResponse($fileName, $grid->getExcelFile($fileName));
    }   
    
    public function uploadAction(){
        $megaImgFolder = Mage::helper('slider')->getMegaImageFolder();
        $imgtype       = $this->getRequest()->getParam('imgtype',false) ;
        if(isset($_FILES['image']['name']) and (file_exists($_FILES['image']['tmp_name']))) {
            try {
                $uploader = new Varien_File_Uploader('image');
                $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
                $uploader->setAllowRenameFiles(true);
                // setAllowRenameFiles(true) -> move your file in a folder the magento way
                // setAllowRenameFiles(true) -> move your file directly in the $path folder
                $uploader->setFilesDispersion(false);
                $path = Mage::getBaseDir('media') . DS . $megaImgFolder;

                $result = $uploader->save($path, $_FILES['image']['name']);
                $result['path'] = $result['file'];
		$result['url'] = Mage::helper('slider')->getFullMegaImageUrl($result['file']);
                $result['url_path'] = $result['file'];                
                $result['img_type'] = $imgtype;
                
            }catch(Exception $e) {
                $result = array(
                'error' => $e->getMessage(),
                'errorcode' => $e->getCode());
            }
        }        
        echo Mage::helper('core')->jsonEncode($result);
        exit;
    }
    
}
